package lx.utils.http.TextRequest;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

import lx.utils.http.TextRequest.DataHull.DataStatus;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

class HttpHandler {
    
    private int mReadTimeOut;
    private int mConnectTimeOut;

    HttpHandler(int readTimeOut, int connectTimeOut) {
        mReadTimeOut = readTimeOut;
        mConnectTimeOut = connectTimeOut;
    }

    HttpHandler() {
    }
    
    public void doGet(DataHull dataHull) {
        doGet(dataHull, null);
    }

    // TODO: handle redirect, support proxy
    public void doGet(DataHull dataHull, HashMap<String, String> headers) {
        URI uri = dataHull.getRequestURI();
        if (uri == null) {
            return;
        }

        String result = null;
        InputStream is = null;
        HttpGet httpGet = new HttpGet(uri);
        DefaultHttpClient httpClient = new DefaultHttpClient();

        if (mConnectTimeOut > 0) {
            httpClient.getParams().setParameter(
                    CoreConnectionPNames.CONNECTION_TIMEOUT, mConnectTimeOut);
        }
        if (mReadTimeOut > 0) {
            httpClient.getParams().setParameter(
                    CoreConnectionPNames.SO_TIMEOUT, mReadTimeOut);
        }
        setHeaders(httpGet, headers);

        try {
            HttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            dataHull.setHttpStatusCode(statusLine.getStatusCode());

            HttpEntity entity = response.getEntity();
            BufferedHttpEntity bufEntity = new BufferedHttpEntity(entity);
            is = bufEntity.getContent();
            result = this.readString(is);
            if (result == null) {
                dataHull.setDataStatusCode(DataStatus.ERR_DATA_NULL);
            } else {
                dataHull.setOriginData(result);
                dataHull.setDataStatusCode(DataStatus.STATUS_OK);
            }
        } catch (ClientProtocolException e) {
            dataHull.setDataStatusCode(DataStatus.ERR_REQUEST_FAIL);
            e.printStackTrace();
            return;
        } catch (IOException e) {
            dataHull.setDataStatusCode(DataStatus.ERR_REQUEST_FAIL);
            e.printStackTrace();
            return;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
    }

    private String readString(InputStream is) throws IOException {
        if (is == null) {
            return null;
        }

        StringBuilder sb = new StringBuilder();
        InputStreamReader reader = new InputStreamReader(is);
        char[] buf = new char[100];
        int len = 0;
        try {
            while ((len = reader.read(buf)) != -1) {
                sb.append(buf, 0, len);
            }
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
        return sb.toString();
    }

    private void setHeaders(HttpRequestBase request, HashMap<String, String> headers) {
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                request.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

}
